defmodule Iocp.Controllers.HistoryController do
  @moduledoc false

  @behaviour Iocp.Controller

  use Bitwise

  @impl true
  def handle(address, data)

  # 有数据
  def handle(address, [
    second, minute, hour, day, month, year,
    voltage_lo, voltage_hi,    # 电压
    amperage_lo, amperage_hi,    # 电流
    power_lo, power_hi,       # 功率
    consumption_0, consumption_1, consumption_2, consumption_3  # 电度
  ]) do
    Iocp.Dumper.dump(address, [
      datetime: format_datetime(year, month, day, hour, minute, second),
      voltage: (voltage_hi <<< 8) + voltage_lo,
      amperage: (amperage_hi <<< 8) + amperage_lo,
      power: (power_hi <<< 8) + power_lo,
      consumption: [consumption_3, consumption_2, consumption_1, consumption_0] |> Enum.reduce(&((&2 <<< 8) + &1))
    ])
  end

  # 无数据
  def handle(_address, _data) do
    # TODO
  end

  defp format_datetime(year, month, day, hour, minute, second) do
    {{year + 2000, month, day}, {hour, minute, second}}
    |> NaiveDateTime.from_erl!()
    |> NaiveDateTime.to_iso8601()
  end
end
